import _ from "lodash"
import cfg from "../../lib/config/config.js"
import common from "../../lib/common/common.js"

/** 续火群号列表 */
const group = []

/** 群聊续火内容 */
const gp_text = ["续火.", "喵喵喵"]

/** 群聊续火时间表达式 */
const gp_cron = "0 0 0 * * *"

/** 续火好友列表 */
const friend = []

/** 好友续火内容 */
const fl_text = ["续火"]

/** 好友续火时间表达式 */
const fl_cron = "0 0 0 * * *"

/** 发送间隔 单位：秒 */
const cd = 5

/** 通知全部主人 */
const notificationsAll = false

export class df_547 extends plugin {
  constructor() {
    super({
      name: "自动续火",
      dsc: "自动续火",
      task: []
    })
    if (group.length > 0) {
      this.task.push({
        cron: gp_cron,
        name: "[自动续火]群聊续火",
        fnc: () => this.auto_fire(group, gp_text, "群聊续火")
      })
    }
    if (friend.length > 0) {
      this.task.push({
        cron: fl_cron,
        name: "[自动续火]好友续火",
        fnc: () => this.auto_fire(friend, fl_text, "好友续火")
      })
    }
  }

  /**
   * 自动续火
   * @param {Array} targets 群聊或好友列表
   * @param {Array} texts 续火内容数组
   * @param {string} taskDesc 任务描述
   */
  async auto_fire(targets, texts, taskDesc) {
    if (targets.length < 1 || texts.length < 1) return false

    const isGroup = taskDesc.includes("群聊")
    this.informMaster(`开始${taskDesc}\n共：${targets.length}${isGroup ? "个群聊" : "人"}\n预计需要：${targets.length * cd}秒`)

    let Success = 0
    let Failure = 0
    for (const id of targets) {
      const text = _.sample(texts)
      try {
        const sendResult = isGroup ? await Bot.pickGroup(id).sendMsg(text) : await Bot.pickFriend(id).sendMsg(text)
        if (sendResult?.message_id?.length) Success++
        else Failure++
      } catch (error) {
        Failure++
        logger.error(`发送消息失败：${error.message}`)
      }
      await common.sleep(cd * 1000)
    }

    this.informMaster(`${taskDesc}任务完成\n成功：${Success}${isGroup ? "个" : ""} 失败：${Failure}${isGroup ? "个" : ""}`)
  }

  /**
   * 通知主人
   * @param {string} msg 发送的文本
   * @returns 消息id
   */
  async informMaster(msg) {
    let masterQQ = cfg.masterQQ
    if (cfg.master) {
      const master = cfg.master[Bot.uin]
      if (master?.length) {
        masterQQ = master
      }
    }
    if (notificationsAll) {
      if (Bot.sendMasterMsg) {
        return Bot.sendMasterMsg(msg, Bot.uin, cd * 1000)
      } else {
        for (const i of masterQQ) {
          common.relpyPrivate(i, msg, Bot.uin)
          await common.sleep(cd * 1000)
        }
      }
    } else {
      return common.relpyPrivate(masterQQ[0], msg, Bot.uin)
    }
  }
}
